<template>
  <div class="app-container">
    <!--    <el-page-header content="" @back="back" />-->
    <!--    <br>-->
    <el-descriptions class="descriptions-class" title="基本信息" :column="4" border>
      <el-descriptions-item>
        <template slot="label">
          <svg-icon icon-class="name-card" style="margin-right: 3px; width: 15px; height: 15px" />
          爬虫名称
        </template>
        {{ crawlerObj.codeName }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <svg-icon icon-class="catalog" style="margin-right: 3px; width: 15px; height: 15px" />
          项目名称
        </template>
        {{ crawlerObj.projectName }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <svg-icon icon-class="computer" style="margin-right: 3px; width: 15px; height: 15px" />
          服务器
        </template>
        {{ crawlerObj.machine }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <svg-icon icon-class="product" style="margin-right: 3px; width: 15px; height: 15px" />
          类路径
        </template>
        {{ crawlerObj.classpath }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <svg-icon icon-class="time" style="margin-right: 3px; width: 15px; height: 15px" />
          最近运行时间
        </template>
        {{ crawlerObj.lastTime }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <svg-icon icon-class="success" style="margin-right: 3px; width: 15px; height: 15px" />
          入库数量
        </template>
        {{ crawlerObj.count }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <svg-icon icon-class="error" style="margin-right: 3px; width: 15px; height: 15px" />
          警告数量
        </template>
        {{ total }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <svg-icon icon-class="discount" style="margin-right: 3px; width: 15px; height: 15px" />
          所在省份
        </template>
        <span v-if="crawlerObj.areaId !== 0">
          {{ getArea(crawlerObj.areaId) }} ({{ crawlerObj.areaId }})
        </span>
        <span v-else>
          未知
        </span>
      </el-descriptions-item>
    </el-descriptions>

    <el-form :inline="true" class="demo-form-inline" size="small" label-position="right" label-width="80px">
      <el-row>
        <el-col :span="6">
          <el-form-item label="警告类型:">
            <el-select
              v-model="searchObj.type"
              clearable
              placeholder="警告类型"
              @change="fetchDataById"
            >
              <el-option
                v-for="item in types"
                :key="item.type"
                :label="item.type"
                :value="item.type"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="处理状态:">
            <el-select
              v-model="searchObj.status"
              clearable
              @change="changeStatus"
            >
              <el-option
                v-for="item in statusList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="负责人:">
            <el-select v-model="crawlerObj.person" @change="updatePerson">
              <el-option
                v-for="item in personList"
                :key="item.person"
                :label="item.person"
                :value="item.person"
              />
            </el-select>
          </el-form-item>
        </el-col>

      </el-row>

      <el-row>
        <el-col :span="6">
          <el-form-item label="警告时间:">
            <div class="block">
              <el-date-picker
                v-model="gmtCreate"
                type="daterange"
                align="center"
                unlink-panels
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions"
                style="width: 280px"
                @change="changeGmtCreate"
              />
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="备注信息:">
            <el-input v-model="crawlerObj.remarks" suffix-icon="xxx" @change="updateRemarks" />
          </el-form-item>
        </el-col>
        <el-col :span="12" style="display: flex; align-items: center;">
          <el-form-item label="定时任务:">
            <div style="display: flex; justify-content: space-between; width: 100%; line-height: 10px; align-items: center;">
              <el-input v-model="crawlerObj.scheduledName" :disabled="scheduledDisabled" suffix-icon="xxx" />
              <el-button v-if="loading" type="warning" size="mini" disabled style="margin-left: 10px; height: 30px">加载中...</el-button>
              <el-button
                v-else-if="scheduledButton"
                type="danger"
                size="mini"
                style="margin-left: 10px; height: 30px"
                @click="unupdateScheduledName"
              >
                解绑
              </el-button>
              <el-button
                v-else
                type="success"
                size="mini"
                style="margin-left: 10px; height: 30px"
                @click="updateScheduledName"
              >
                绑定
              </el-button>
              <span style="color:#999; display: inline-block; margin-left: 10px; white-space: nowrap;">
                (仅支持xxl-job)
              </span>
              <span>
                <el-button
                  v-if="crawlerObj.scheduledId"
                  ref="linkOut"
                  type="info"
                  plain
                  size="mini"
                  icon
                  style="margin-left: 20px; font-size: 1px; line-height: 1px; padding: 4px; border-radius: 2px;"
                  @click="linkOutForScheduled"
                >
                  <svg-icon icon-class="link" style="margin-right: 5px; width: 10px; height: 10px" />
                  查看日志
                </el-button>
              </span>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" style="display: flex; justify-content: space-between; margin-bottom: 8px;">
      <el-col :span="1.5">
        <el-button
          v-if="searchObj.status === 0"
          ref="ignore"
          size="mini"
          type="warning"
          icon
          @click="multipleHandle(2)"
        >
          <svg-icon icon-class="hide" class="el-icon--left" style="width: 13px; height: 13px" />
          批量忽略</el-button>
        <el-button
          v-else
          ref="unIgnore"
          size="mini"
          type="danger"
          icon
          @click="multipleHandle(0)"
        >
          <svg-icon icon-class="return" class="el-icon--left" style="width: 13px; height: 13px" />
          批量撤销</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-dropdown
          v-if="searchObj.status === 0"
          show-timeout="0"
          @command="oneTouchIgnore"
        >
          <el-button
            ref="oneTouchIgnore"
            size="mini"
            type="success"
            icon
            :disabled="oneTouchDisabled"
          >
            <svg-icon icon-class="business-icon-buyers-club-fill" class="el-icon--left" style="width: 13px; height: 13px" />
            一键忽略<i class="el-icon-arrow-down el-icon--right" />
          </el-button>
          <el-dropdown-menu slot="dropdown" style="width: 120px">
            <el-dropdown-item
              v-for="item in dropdownList"
              :key="item.dropdown"
              :command="item.dropdown"
            >{{ item.dropdown }}</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
      <el-col v-if="crawlerObj.spiderType === 0" :span="1.5">
        <router-link :to="'/analysis/detail/' + id">
          <el-button
            ref="analysisBtn"
            size="mini"
            type="primary"
            icon="el-icon-s-data"
          >
            爬虫分析
          </el-button>
        </router-link>
      </el-col>
      <div class="right-toolbarClass">
        <right-toolbar @queryTable="flashList" />
      </div>
    </el-row>

    <!--列表-->
    <el-table
      ref="tableList"
      v-loading="loading"
      :data="errList"
      :header-cell-style="headStyle"
      :cell-style="cellStyle"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="70" align="center" />
      <el-table-column prop="dataId" label="数据id" width="100" />
      <el-table-column prop="tableName" label="表名称" width="150" />
      <el-table-column prop="className" label="类名称" width="200" />
      <el-table-column prop="gmtCreate" label="警告时间" width="180" />
      <el-table-column prop="type" label="警告类型" width="150">
        <template slot-scope="scope">
          <div v-if="scope.row.status === 0">
            <el-tag
              v-for="(item, index) in scope.row.typeList"
              :key="index"
              :text="item"
              type="danger"
              style="margin-right: 5px; margin-bottom: 5px; margin-top: 5px"
            >{{ item }}</el-tag>
          </div>
          <div v-else-if="scope.row.status === 1">
            <el-tag
              v-for="(item, index) in scope.row.typeList"
              :key="index"
              :text="item"
              type="success"
              style="margin-right: 5px; margin-bottom: 5px; margin-top: 5px"
            >{{ item }}</el-tag>
          </div>
          <div v-else>
            <el-tag
              v-for="(item, index) in scope.row.typeList"
              :key="index"
              :text="item"
              type="warning"
              style="margin-right: 5px; margin-bottom: 5px; margin-top: 5px"
            >{{ item }}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="reason" label="警告原因" />
      <el-table-column prop="status" label="处理状态" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 0" type="danger">未处理</el-tag>
          <el-tag v-else-if="scope.row.status === 1" type="success">已处理</el-tag>
          <el-tag v-else type="warning">已忽略</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="120" align="center">
        <template slot-scope="scope">
          <el-button icon type="warning" size="mini" @click="fixDialogOpen(scope.row)">
            <svg-icon icon-class="info" style="margin-right: 1px; width: 15px; height: 15px; padding-top: 2px" />
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      title="数据详情"
      :visible.sync="fixDialogVisible"
      :close-on-click-modal="true"
      class="dialog"
      @close="closeFixDialog"
    >
      <div style="margin-bottom: 20px">
        <span style="color: red; font-size: 20px">警告原因：{{ errReason }}</span>
      </div>

      <div class="table1">
        <label>原始数据</label>
        <el-table
          ref="tableList"
          v-loading="loading2"
          :data="dataObj"
          border
          stripe
          :header-cell-style="headStyle"
          :cell-style="cellStyle2"
        >

          <el-table-column prop="dataId" label="数据ID" width="120" align="center" />
          <el-table-column prop="title" label="标题" width="200" align="center" />
          <el-table-column v-if="crawlerObj.spiderType === 0" prop="location" label="来源地区" width="100" align="center" />
          <el-table-column prop="author" label="来源" :show-overflow-tooltip="true" />
          <el-table-column v-if="crawlerObj.spiderType === 5" prop="level" label="来源等级" width="100" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.level === 1">国家级</span>
              <span v-else-if="scope.row.level === 2">省级</span>
              <span v-else-if="scope.row.level === 3">市级</span>
            </template>
          </el-table-column>
          <el-table-column v-if="crawlerObj.spiderType === 5" prop="tag" label="标签" width="200" align="center">
            <template slot-scope="scope">
              <el-tag
                v-for="tag in scope.row.tags"
                :key="tag"
                :type="tag"
                class="fixDialog-tag"
              >
                {{ tag }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column v-if="crawlerObj.spiderType === 0" prop="cateId" label="分类ID" width="100" align="center">
            {{ cateLabel }}
          </el-table-column>
          <el-table-column prop="pubtime" label="发布时间" width="165" align="center" />
          <el-table-column prop="addTime" label="入库时间" width="180" align="center" />
          <el-table-column prop="info" label="正文" width="100" align="center">
            <template slot-scope="scope">
              <el-badge
                ref="elBadge"
                :hidden="elBadgeVisabled"
                value="1"
                style="display: inline"
              >
                <el-button
                  ref="previewHtml"
                  type="primary"
                  plain
                  size="mini"
                  icon
                  @click="previewHtml"
                >
                  <svg-icon icon-class="view-fill" style="margin-right: 3px; width: 15px; height: 15px" />
                  预览
                </el-button>
              </el-badge>
              <span v-if="scope" />
            </template>
          </el-table-column>
          <el-table-column prop="intro" label="附件" width="100" align="center">
            <el-button
              ref="downloadFile"
              type="primary"
              plain
              size="mini"
              icon
              @click="downloadFile"
            >
              <svg-icon icon-class="download1" style="margin-right: 3px; width: 15px; height: 15px" />
              下载
            </el-button>
          </el-table-column>
          <el-table-column prop="outurl" label="链接" width="100" align="center">
            <template slot-scope="scope">
              <el-button ref="linkOut" type="primary" plain size="mini" icon @click="linkOut(scope.row.outurl)">
                <svg-icon icon-class="link" style="margin-right: 5px; width: 12px; height: 12px" />
                跳转
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" align="center">
            <el-button v-if="updateDialogVisible" icon type="warning" size="mini" @click="updateStatus(2)">
              <svg-icon icon-class="hide" style="margin-right: 3px; width: 15px; height: 15px" />
              忽略
            </el-button>
            <el-button v-else icon type="danger" size="mini" @click="updateStatus(0)">
              <svg-icon icon-class="return" style="margin-right: 3px; width: 15px; height: 15px" />
              撤销
            </el-button>
          </el-table-column>
        </el-table>
      </div>
      <br>
      <br>

      <div class="table2">
        <label v-if="updateDialogVisible">修改数据</label>
        <el-form v-if="updateDialogVisible" ref="formData" :model="updateObj[0]" :rules="rules">
          <el-table
            ref="tableList2"
            v-loading="loading2"
            :data="updateObj"
            border
            stripe
            :header-cell-style="headStyle"
            :cell-style="cellStyle"
          >
            <el-table-column prop="dataId" label="数据ID" width="120" align="center" />
            <el-table-column prop="title" label="标题" width="200" :show-overflow-tooltip="true" align="center">
              <template slot-scope="scope">
                <el-form-item prop="title">
                  <el-input v-model="scope.row.title" name="title" @blur="handleBlur('title')" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column v-if="crawlerObj.spiderType === 0" prop="location" label="来源地区" width="100" align="center">
              <template slot-scope="scope">
                <el-form-item prop="location">
                  <el-input v-model="scope.row.location" name="location" @blur="handleBlur('location')" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="author" label="来源" align="center">
              <template slot-scope="scope">
                <div class="el-table-wrapper">
                  <el-form-item prop="author">
                    <el-input v-model="scope.row.author" name="author" @blur="handleBlur('author')" />
                  </el-form-item>
                </div>
              </template>
            </el-table-column>
            <el-table-column v-if="crawlerObj.spiderType === 5" prop="level" label="来源等级" width="100" align="center">
              <template slot-scope="scope">
                <el-select v-model="scope.row.level" @blur="handleBlur('level')">
                  <el-option
                    v-for="item in levels"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column v-if="crawlerObj.spiderType === 5" prop="tag" label="标签" width="200" align="center">
              <template slot-scope="scope">
                <el-select v-model="scope.row.tags" multiple @blur="handleBlur('tags')">
                  <el-option
                    v-for="item in tags"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column v-if="crawlerObj.spiderType === 0" prop="cateId" label="分类ID" width="100" align="center">
              <template slot-scope="scope">
                <el-form-item prop="cateId">
                  <el-select v-model="scope.row.cateId" @blur="handleBlur('cateId')">
                    <el-option
                      v-for="item in cateIds"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="pubtime" label="发布时间" width="165" align="center">
              <template slot-scope="scope">
                <el-form-item prop="pubtime">
                  <el-date-picker
                    v-model="scope.row.pubtime"
                    type="date"
                    style="width: 140px"
                    value-format="yyyy-MM-dd"
                    :clearable="false"
                    @blur="handleBlur('pubtime')"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="addTime" label="入库时间" width="180" align="center" />
            <el-table-column prop="info" label="正文" width="100" align="center">
              <el-button type="primary" plain size="mini" icon @click="dialogInfoVisible = true">
                <svg-icon icon-class="edit1" style="margin-right: 3px; width: 15px; height: 15px" />
                修改
              </el-button>
            </el-table-column>
            <el-table-column prop="intro" label="附件" width="100" align="center">
              <el-button
                ref="openUploadFile"
                type="primary"
                plain
                size="mini"
                icon
                @click="openUploadFile"
              >
                <svg-icon icon-class="upload1" style="margin-right: 3px; width: 15px; height: 15px" />
                上传</el-button>
            </el-table-column>
            <el-table-column prop="outurl" label="链接" width="100" align="center">
              <el-button type="primary" plain size="mini" icon @click="dialogUrlVisible = true">
                <svg-icon icon-class="editor-eraser" style="margin-right: 5px; width: 12px; height: 12px" />
                更正
              </el-button>
            </el-table-column>
            <el-table-column label="操作" width="100" align="center">
              <el-button type="success" size="mini" icon @click="updateCommit">
                <svg-icon icon-class="save-fill" style="margin-right: 3px; width: 15px; height: 15px" />
                保存
              </el-button>
            </el-table-column>
          </el-table>

          <el-dialog
            v-if="updateObj.length"
            title="输入数据正文内容"
            :visible.sync="dialogInfoVisible"
            :close-on-click-modal="false"
            append-to-body
          >
            <el-form-item prop="info">
              <textarea
                v-model="updateObj[0].info"
                style="height: 500px;width: 900px;"
              />
            </el-form-item>
            <span slot="footer" class="dialog-footer">
              <el-button @click="cancelEditInfo">取 消</el-button>
              <el-button
                type="primary"
                @click="updateInfo"
              >确 定</el-button>
            </span>
          </el-dialog>

          <el-dialog
            v-if="updateObj.length"
            title="输入数据访问链接"
            :visible.sync="dialogUrlVisible"
            :close-on-click-modal="false"
            append-to-body
          >
            <el-form-item prop="outurl">
              <el-input
                v-model="updateObj[0].outurl"
                style="width: 900px;"
              />
            </el-form-item>
            <span slot="footer" class="dialog-footer">
              <el-button @click="cancelEditHtml">取 消</el-button>
              <el-button
                type="primary"
                @click="closeEditHtml('outurl')"
              >确 定</el-button>
            </span>
          </el-dialog>
        </el-form>
      </div>
    </el-dialog>

    <!-- 分页组件 -->
    <el-pagination
      background
      :current-page="page"
      :total="total"
      :page-size="limit"
      :page-sizes="[10, 20, 50, 100, 1000]"
      prev-text="上一页"
      next-text="下一页"
      style="padding: 30px 0; text-align: center"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="changePageSize"
      @current-change="changeCurrentPage"
    />

    <!-- 弹窗模板 -->
    <modal name="detail-modal">
      <h2 style="font-size: 20px; text-align: center;">预览</h2>
      <!-- iframe 内容 -->
      <iframe :srcdoc="iframeContent" />
    </modal>

    <!-- 下载弹窗 -->
    <modal name="download-modal">
      <h2 style="font-size: 20px; text-align: center;">附件</h2>
      <!-- 分割线 -->
      <div class="separator" />
      <!-- table 内容 -->
      <div class="fileTableClass">
        <el-table
          ref="downLoadList"
          :data="downloadFiles"
          border
          stripe
          :header-cell-style="headStyle"
          :cell-style="cellStyle2"
        >
          <el-table-column label="序号" width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="fileName" label="文件名称" align="center" />
          <el-table-column prop="fileTime" label="首次上传时间" width="180" align="center" />
          <el-table-column prop="fileType" label="文件类型" width="80" align="center" />
          <el-table-column label="操作" width="80">
            <template slot-scope="scope">
              <el-button ref="openDownloadButton" size="mini" icon @click="openDownload(scope.row.fileUrl)">
                预览
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <input ref="fileInput" type="file" multiple style="display: none" @change="handleFileChanged" @click="clearFileInput">
      <el-button ref="chooseFile" type="primary" size="small" style="margin: 10px 10px 0 10px" icon @click="chooseFile">
        选择文件
      </el-button>
      <el-button ref="doUploadFile" type="primary" size="small" style="margin: 10px 10px 0 0" icon @click="doUploadFile">
        上传文件
      </el-button>

      <!-- table 内容 -->
      <div class="fileTableClass">
        <el-table
          ref="uploadList"
          :data="uploadFiles"
          border
          stripe
          :header-cell-style="headStyle"
          :cell-style="cellStyle2"
        >
          <el-table-column label="序号" width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="fileName" label="文件名称" align="center" />
          <el-table-column prop="fileTime" label="本次上传时间" width="180" align="center" />
          <el-table-column prop="fileType" label="文件类型" width="80" align="center" />
          <el-table-column label="操作" width="80">
            <template slot-scope="scope">
              <el-button ref="openDownloadButton" size="mini" icon @click="delteUploadFile(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </modal>

  </div>
</template>

<script>
import crawlerDetailApi from '@/api/crawler/crawlerDetail'
import crawlerApi from '@/api/crawler/crawler'
// import { MessageBox } from 'element-ui'
import variables from '@/styles/variables.scss'
import moment from 'moment'

export default {
  name: 'CrawlerDetail',
  data() {
    return {
      id: 0,
      total: 0, // 数据库总记录数
      page: 1, // 默认页码
      limit: 10, // 每页记录数

      crawlerObj: { // 数据对象
        id: this.$route.params.id,
        codeName: '',
        projectName: '',
        machine: '',
        spiderType: 0,
        lastTime: '',
        person: '',
        count: '',
        errCount: '',
        classpath: '',
        remarks: '',
        scheduledId: '',
        scheduledName: '',
        isJava: '',
        isPdf: false,
        url: '',
        areaId: 0
      },
      errList: [], // 错误数据list
      loading: true, // detail界面table
      loading2: true, // detail弹窗界面table
      scheduledDisabled: true,
      scheduledButton: true,

      searchObj: { // 查询条件
        id: this.$route.params.id,
        type: '',
        status: 0,
        startTime: '',
        endTime: ''
      },
      iframeContent: '', // info
      downloadFiles: [], // 下载附件
      uploadFiles: [], // 上传附件

      statusList: [
        {
          value: 0,
          label: '未处理'
        },
        {
          value: 1,
          label: '已处理'
        },
        {
          value: 2,
          label: '已忽略'
        }
      ],

      types: [], // 错误类型列表
      personList: [], // 负责人列表

      fixDialogVisible: false, // 修改弹窗
      updateDialogVisible: false, // 修改弹窗中的下半部分
      dialogInfoVisible: false, // 修改info弹窗
      dialogUrlVisible: false, // 修改outurl弹窗

      dataObj: [], // 展示数据详情用
      updateObj: [], // 展示修改数据详情用
      errReason: '', // 弹窗展示用的错误原因
      errTypeList: [], // 弹窗展示用的错误类型list
      elBadgeVisabled: true, // 小红点是否隐藏

      multipleSelection: [], // 多选
      pickerOptions: { // 时间选择器
        shortcuts: [
          {
            text: '当前日期',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }]
      },
      gmtCreate: [], // 选中的时间

      cateIds: [
        {
          value: 1,
          label: '招标'
        },
        {
          value: 2,
          label: '中标'
        },
        {
          value: 3,
          label: '开标记录'
        },
        {
          value: 4,
          label: '答疑补遗澄清变更'
        },
        {
          value: 5,
          label: '中标变更'
        },
        {
          value: 6,
          label: '废标流标终止'
        },
        {
          value: 7,
          label: '资格预审结果'
        },
        {
          value: -1,
          label: '未分类别'
        }
      ],
      cateLabel: '', // 分类

      tags: [
        {
          value: '政策法规',
          label: '政策法规'
        },
        {
          value: '政策解读',
          label: '政策解读'
        },
        {
          value: '市场分析',
          label: '市场分析'
        },
        {
          value: '行业规划',
          label: '行业规划'
        },
        {
          value: '地区规划',
          label: '地区规划'
        },
        {
          value: '招标办法与评标规则',
          label: '招标办法与评标规则'
        },
        {
          value: '宏观经济',
          label: '宏观经济'
        },
        {
          value: '财政信息',
          label: '财政信息'
        },
        {
          value: '债务信息',
          label: '债务信息'
        },
        {
          value: '政府工作报告',
          label: '政府工作报告'
        },
        {
          value: '其他',
          label: '其他'
        }
      ],
      levelLabel: '', // 来源等级
      levels: [
        {
          value: 1,
          label: '国家级'
        },
        {
          value: 2,
          label: '省级'
        },
        {
          value: 3,
          label: '市级'
        }
      ],

      dropdownList: [], // 一键忽略list列表
      oneTouchDisabled: false, // 一键忽略按钮是否禁用
      formData: {}, // 校验表单
      rules: { // 校验规则
        title: {
          required: true,
          message: '不能为空',
          trigger: 'change'
        },
        // location: {
        //   required: true,
        //   message: '不能为空',
        //   trigger: 'change'
        // },
        author: {
          required: true,
          message: '不能为空',
          trigger: 'change'
        },
        // cateId: {
        //   required: true,
        //   message: '不能为空',
        //   trigger: 'change'
        // },
        pubtime: {
          required: true,
          message: '不能为空',
          trigger: 'change'
        },
        outurl: {
          required: true,
          message: '不能为空',
          trigger: 'change'
        }
        // tags: {
        //   required: true,
        //   message: '不能为空',
        //   trigger: 'change'
        // }
      },
      cities: [
        {
          value: 1,
          label: '中国'
        }, {
          value: 2,
          label: '北京'
        }, {
          value: 3,
          label: '安徽'
        }, {
          value: 4,
          label: '福建'
        }, {
          value: 5,
          label: '甘肃'
        }, {
          value: 6,
          label: '广东'
        }, {
          value: 7,
          label: '广西'
        }, {
          value: 8,
          label: '贵州'
        }, {
          value: 9,
          label: '海南'
        }, {
          value: 10,
          label: '河北'
        }, {
          value: 11,
          label: '河南'
        }, {
          value: 12,
          label: '黑龙江'
        }, {
          value: 13,
          label: '湖北'
        }, {
          value: 14,
          label: '湖南'
        }, {
          value: 15,
          label: '吉林'
        }, {
          value: 16,
          label: '江苏'
        }, {
          value: 17,
          label: '江西'
        }, {
          value: 18,
          label: '辽宁'
        }, {
          value: 19,
          label: '内蒙古'
        }, {
          value: 20,
          label: '宁夏'
        }, {
          value: 21,
          label: '青海'
        }, {
          value: 22,
          label: '山东'
        }, {
          value: 23,
          label: '山西'
        }, {
          value: 24,
          label: '陕西'
        }, {
          value: 25,
          label: '上海'
        }, {
          value: 26,
          label: '四川'
        }, {
          value: 27,
          label: '天津'
        }, {
          value: 28,
          label: '西藏'
        }, {
          value: 29,
          label: '新疆'
        }, {
          value: 30,
          label: '云南'
        }, {
          value: 31,
          label: '浙江'
        }, {
          value: 32,
          label: '重庆'
        }, {
          value: 33,
          label: '香港'
        }, {
          value: 34,
          label: '台湾'
        }, {
          value: 35,
          label: '澳门'
        }
      ]
    }
  },

  computed: {
    getArea() {
      return function(areaId) {
        let label = ''
        this.cities.forEach(city => {
          if (city.value === areaId) {
            label = city.label
          }
        })
        return label
      }
    }
  },

  created() {
    if (this.$route.params.id && this.$route.params.count) {
      this.id = this.$route.params.id
      this.fetchDataById()
      this.fetchList()
    }
  },

  methods: {
    fetchDataById() {
      this.fetchList()
      this.loading = true
      crawlerDetailApi.crawlerDetail(this.page, this.limit, this.searchObj).then((response) => {
        this.crawlerObj = response.data.result // 基本信息填充
        this.crawlerObj.count = this.$route.params.count // 从路径中取出上个页面传过来的count值
        this.crawlerObj.isPdf = response.data.result.isPdf !== '0' // 从请求结果中取出isPdf进行赋值
        if (response.data.result.errList.list.length > 0) { // 判断errList是否为空，并进行赋值
          this.errList = response.data.result.errList.list
          this.total = response.data.result.errList.total
        } else {
          this.errList = []
          this.total = 0
        }
        this.loading = false
        this.scheduledDisabled = !!this.crawlerObj.scheduledName // 定时任务输入框是否启用修改
        this.scheduledButton = !!this.crawlerObj.scheduledName // 定时任务绑定解绑按钮的显示
      })
    },

    fetchList() {
      const formData = {
        id: this.id,
        status: this.searchObj.status,
        startTime: this.searchObj.startTime,
        endTime: this.searchObj.endTime
      }
      crawlerDetailApi.crawlerDetailTypes(formData).then((response) => {
        this.types = response.data.result
      })
      crawlerApi.getPersonList().then((response) => {
        this.personList = response.data.result
      })
      crawlerApi.getDropdownList(this.id).then((response) => {
        this.dropdownList = response.data.result
      })
    },

    // 刷新列表按钮
    flashList() {
      this.fetchDataById()
      // this.fetchList()
    },

    // 修改负责人
    updatePerson() {
      crawlerApi.updatePerson(this.id, this.crawlerObj.person).then((response) => {
        if (response.code === 200) {
          this.$message({
            message: '负责人修改成功',
            type: 'success'
          })
        }
      }).catch((err) => {
        this.$message({
          message: err.message,
          type: 'error'
        })
      })
    },

    // 修改备注信息
    updateRemarks() {
      if (this.crawlerObj.remarks) {
        const date = new Date()
        const year = date.getFullYear()
        const month = (date.getMonth() + 1).toString().padStart(2, '0')
        const day = date.getDate().toString().padStart(2, '0')
        const result = `${year}-${month}-${day}`
        this.crawlerObj.remarks = this.crawlerObj.remarks + ' ' + result
      } else {
        this.crawlerObj.remarks = ''
      }
      crawlerApi.updateRemarks(this.id, this.crawlerObj.remarks).then((response) => {
        if (response.code === 200) {
          this.$message({
            message: '备注修改成功',
            type: 'success'
          })
        }
      }).catch((err) => {
        this.$message({
          message: err.message,
          type: 'error'
        })
      })
    },

    // 绑定定时任务
    updateScheduledName() {
      if (!this.crawlerObj.scheduledName) {
        this.$message.warning('任务名称为空')
      } else {
        crawlerApi.updateScheduledName(this.id, this.crawlerObj.scheduledName, this.crawlerObj.machine).then((response) => {
          if (response.code === 200) {
            this.$message({
              message: '绑定成功',
              type: 'success'
            })
            this.crawlerObj.scheduledId = response.data.scheduledId
            this.fetchDataById()
          }
        })
      }
    },

    // 解绑定时任务
    unupdateScheduledName() {
      this.$confirm('是否解绑?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发送解绑请求
        crawlerApi.unupdateScheduledName(this.id).then((response) => {
          if (response.code === 200) {
            this.$message({
              message: '解绑成功',
              type: 'success'
            })
            this.crawlerObj.scheduledName = ''
            this.fetchDataById()
          }
        })
      })
    },

    // 处理状态
    changeStatus() {
      this.searchObj.type = ''
      this.fetchDataById()
    },

    // 修改爬虫是否为pdf类型
    changePdf(val) {
      if (val) {
        this.$confirm('是否要切换为pdf爬虫？将会删除所有info的错误日志，请谨慎选择', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 发送修改请求
          crawlerApi.changePdf(this.id).then((response) => {
            if (response.code === 200) {
              this.$message({
                message: '切换成功',
                type: 'success'
              })
              this.fetchDataById()
              this.fetchList()
            }
          })
        }).catch(() => {
          this.crawlerObj.isPdf = false
        })
      } else {
        // 切换为不是pdf
        crawlerApi.changePdf2(this.id).then((response) => {
          if (response.code === 200) {
            this.$message({
              message: '切换成功',
              type: 'success'
            })
            this.fetchDataById()
            this.fetchList()
          }
        })
      }
    },

    // 打开修改弹窗
    fixDialogOpen(row) {
      if (!row.dataId > 0) {
        this.$message.warning('数据id无效')
      } else {
        this.fixDialogVisible = true // 打开弹窗
        const status = row.status
        if (status === 0) {
          this.updateDialogVisible = true // 展示下半部分修改
        } else {
          this.updateDialogVisible = false // 隐藏下半部分修改
        }
        this.getCrawlerDataById(row.did, row.dataId, row.tableName)
        this.errReason = row.reason // 错误原因赋值
        this.errTypeList = row.typeList // 错误类型list赋值
        // 判断list中是否有info，预览按钮是否需要显示小红点
        this.elBadgeVisabled = !this.errTypeList.includes('info')
      }
    },

    // 点击详情获取数据信息
    getCrawlerDataById(did, dataId, tableName) {
      // 发送请求
      const searchObj = {
        did: did,
        dataId: dataId,
        tableName: tableName,
        spiderType: this.crawlerObj.spiderType
      }
      crawlerDetailApi.crawlerDataById(searchObj).then((response) => {
        const dataObj = response.data.result
        if (dataObj[0].dataId === null) {
          this.$message.error('数据id无效')
        }

        this.dataObj = JSON.parse(JSON.stringify(dataObj)) // 将返回的信息复制两份
        this.updateObj = JSON.parse(JSON.stringify(dataObj)) // 将返回的信息复制两份
        this.dataObj[0].did = did // 将did的值赋给具体数据
        this.cateLabel = this.getCateLabel(this.dataObj[0].cateId) // 将cateId的值转变成中文
        this.levelLabel = this.getLevelLabel(this.dataObj[0].level) // 将level的值转变成中文
        this.downloadFiles = this.dataObj[0].fileList // 将附件赋值
        this.uploadFiles = [] // 每次点开一条新的数据时需要置空上传栏
        this.updateObj[0].did = did // 将did的值赋给具体数据
        this.updateObj[0].tableName = tableName // 将tableName的值赋给具体数据
        if (JSON.parse(JSON.stringify(dataObj))[0].pubtime !== '') {
          this.updateObj[0].pubtime = moment(JSON.parse(JSON.stringify(dataObj))[0].pubtime).format('YYYY-MM-DD')
        }
        this.loading2 = false
      })
    },

    // 获取cateId的中文分类
    getCateLabel(cateId) {
      const cateLabel = this.cateIds.find(cate => cate.value === cateId)
      return cateLabel ? cateLabel.label : ''
    },

    // 获取cateId的中文分类
    getLevelLabel(level) {
      const levelLabel = this.levels.find(cate => cate.value === level)
      return levelLabel ? levelLabel.label : ''
    },

    // 关闭修改弹窗
    closeFixDialog() {
      this.errTypeList = []
      this.dataObj = []
      this.updateObj = []
      this.loading2 = true
    },

    // 附件下载
    downloadFile() {
      this.$modal.show('download-modal')
      this.$nextTick(() => {
        this.$refs.downloadFile.$el.blur()
      })
    },

    // 打开附件链接窗口下载
    openDownload(url) {
      window.open(url + '?download=0')
      this.$nextTick(() => {
        this.$refs.openDownloadButton.$el.blur()
      })
    },

    // 预览正文弹窗
    previewHtml() {
      if (!this.elBadgeVisabled) {
        this.elBadgeVisabled = true // 关闭小红点显示
        this.$refs.elBadge.$forceUpdate()
      }

      if (this.dataObj[0].info === '') {
        this.$message({
          message: 'info为空',
          type: 'warning'
        })
      } else {
        this.iframeContent = this.dataObj[0].info
        this.$modal.show('detail-modal')

        // MessageBox.alert(this.dataObj[0].info, '预览', {
        //   dangerouslyUseHTMLString: true, // 允许html文本
        //   closeOnClickModal: true, // 允许点击空白处关闭弹窗
        //   customClass: 'custom-box' // css样式
        // }).catch(() => {
        //   this.$refs.elBadge.$children[0].$forceUpdate()
        // })
      }
      this.$nextTick(() => {
        this.$refs.previewHtml.$el.blur()
      })
    },

    // 跳转链接
    linkOut(outurl) {
      window.open(outurl, '_blank', 'noreferrer,noopener')
      this.$nextTick(() => {
        this.$refs.linkOut.$el.blur()
      })
    },

    // 跳转定时任务链接
    linkOutForScheduled() {
      const outurl = 'http://192.168.1.221:8080/xxl-job-admin/joblog?jobId=' + this.crawlerObj.scheduledId
      window.open(outurl, '_blank')
      this.$nextTick(() => {
        this.$refs.linkOut.$el.blur()
      })
    },

    // 忽略数据
    updateStatus(status) {
      crawlerDetailApi.updateStatus(status, this.dataObj[0].did).then((response) => {
        if (response.code === 200) {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.fetchDataById() // 更新列表
          // this.fetchList()
          this.fixDialogVisible = false
        } else {
          this.$message({
            message: response.message,
            type: 'error'
          })
        }
      })
    },

    // 校验单个字段
    handleBlur(name) {
      this.$nextTick(() => {
        // 校验单个字段，调用validateField方法，单个参数就是校验某个字段，多个参数时，第二个参数无内容表示校验通过
        this.$refs.formData.validateField(name)
      })
    },

    // 打开文件上传展示弹窗
    openUploadFile() {
      this.$modal.show('download-modal')
      this.$nextTick(() => {
        this.$refs.openUploadFile.$el.blur()
      })
    },

    // 附件上传
    chooseFile() {
      // 触发隐藏的文件选择框
      this.$refs.fileInput.click()
      this.$nextTick(() => {
        this.$refs.chooseFile.$el.blur()
      })
    },

    // 清除文件选择器的选择
    clearFileInput() {
      this.$refs.fileInput.value = null
    },

    // 将选择的文件传入临时存储
    handleFileChanged(event) {
      const file = event.target.files[0]
      const fileName = file.name
      const fileType = fileName.substring(fileName.lastIndexOf('.') + 1)
      // 禁止选择重复的文件
      const index = this.uploadFiles.findIndex(file => file.fileName === fileName && file.fileType === fileType)
      if (index !== -1) {
        alert('文件重复')
        return
      }
      const fileTime = moment().format('YYYY-MM-DD HH:mm:ss')
      const newObj = {
        file: file,
        fileName: fileName,
        fileType: fileType,
        fileTime: fileTime
      }
      this.uploadFiles.push(newObj)
    },

    // 删除待上传的文件
    delteUploadFile(row) {
      const fileName = row.fileName
      const fileType = row.fileType
      const index = this.uploadFiles.findIndex(file => file.fileName === fileName && file.fileType === fileType)
      if (index !== -1) {
        this.uploadFiles.splice(index, 1)
      }
    },

    // 上传操作
    doUploadFile() {
      if (this.uploadFiles.length === 0) {
        alert('请选择文件')
        return
      }

      const formData = new FormData()
      formData.append('id', this.updateObj[0].dataId)
      formData.append('tableName', this.updateObj[0].tableName)
      this.uploadFiles.forEach(file => formData.append('files', file.file))
      crawlerDetailApi.uploadFile(formData).then((response) => {
        this.$message({
          message: response.message,
          type: 'success'
        })
        this.$refs.fileInput.value = null // 置空文件选择框
        this.uploadFiles = [] // 置空文件暂存列表
        // 刷新原始数据
        this.getCrawlerDataById(this.updateObj[0].did, this.updateObj[0].dataId, this.updateObj[0].tableName)
      }).catch(() => {
        this.$refs.fileInput.value
        this.uploadFiles = [] // 置空文件暂存列表
      })
    },

    // 外部链接取消按钮
    cancelEditHtml() {
      this.dialogUrlVisible = false
      setTimeout(() => {
        this.updateObj[0].outurl = this.dataObj[0].outurl
      }, 500)
    },

    // 关闭弹窗
    closeEditHtml(name) {
      this.$nextTick(() => {
        // 校验单个字段，调用validateField方法，单个参数就是校验某个字段，多个参数时，第二个参数无内容表示校验通过
        this.$refs.formData.validateField(name, (err) => {
          if (!err) {
            this.dialogInfoVisible = false
            this.dialogUrlVisible = false
          }
        })
      })
    },

    // 更新正文
    updateInfo() {
      this.dataObj[0].info = this.updateObj[0].info // 手动将刚刚修改的info赋值到原始数据中去
      this.$message({
        message: '更新成功，请预览后保存',
        type: 'success'
      })
      this.dialogInfoVisible = false
    },

    // 取消更新正文按钮
    cancelEditInfo() {
      this.dialogInfoVisible = false
      setTimeout(() => {
        this.updateObj[0].info = this.dataObj[0].info
      }, 500)
    },

    // 提交修改
    updateCommit() {
      this.$refs.formData.validate((err) => {
        // true表示校验通过，false表示校验失败，validate方法是整个表单所有字段都校验
        if (!err) {
          this.$message({
            message: '内容校验不通过',
            type: 'error'
          })
        } else {
          this.$confirm('确定保存?', '提示', {
            cancelButtonText: '取消',
            confirmButtonText: '确定',
            type: 'warning'
          }).then(() => {
            this.updateObj[0].spiderType = this.crawlerObj.spiderType
            return crawlerDetailApi.updateCommit(this.updateObj[0])
          }).then(() => {
            this.fetchDataById() // 刷新列表
            // 更新原始数据
            this.getCrawlerDataById(this.updateObj[0].did, this.updateObj[0].dataId, this.updateObj[0].tableName)
            this.$message({
              type: 'success',
              message: '保存成功'
            })
            this.fixDialogVisible = false
          }).catch((reason) => {
            if (reason === 'cancel') {
              this.$message({
                type: 'info',
                message: '取消保存'
              })
            }
          })
        }
      })
    },

    // 多选
    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    // 批量处理
    multipleHandle(status) {
      if (this.multipleSelection.length === 0) {
        this.$message({
          message: '请选择数据',
          type: 'warning'
        })
      } else {
        // 获取did集合
        const arr = []
        this.multipleSelection.forEach(item => {
          arr.push(item.did)
        })

        // 创建表单
        const formData = new FormData()
        formData.append('status', status)
        formData.append('arr', arr)

        crawlerDetailApi.multipleHandle(formData).then((response) => {
          if (response.code === 200) {
            this.$message({
              message: '处理成功',
              type: 'success'
            })
            this.fetchDataById()
          } else {
            this.$message({
              message: response.message,
              type: 'error'
            })
          }
        })
      }
      if (status === 2) {
        this.$nextTick(() => {
          this.$refs.ignore.$el.blur()
        })
      } else {
        this.$nextTick(() => {
          this.$refs.unIgnore.$el.blur()
        })
      }
    },

    // 一键忽略
    oneTouchIgnore(type) {
      this.oneTouchDisabled = true
      crawlerDetailApi.oneTouchIgnore(this.crawlerObj.id, type).then((response) => {
        if (response.code === 200) {
          this.oneTouchDisabled = false
          this.$message({
            message: '操作成功，已忽略 ' + response.data.result + ' 条数据',
            type: 'success'
          })
          this.fetchDataById()
        } else {
          this.oneTouchDisabled = false
          this.$message({
            message: '操作失败，请联系管理员',
            type: 'error'
          })
        }
      })
    },

    // 错误时间筛选
    changeGmtCreate() {
      if (this.gmtCreate != null) {
        this.searchObj.startTime = this.gmtCreate[0]
        this.searchObj.endTime = this.gmtCreate[1]
        this.fetchDataById()
      } else {
        this.searchObj.startTime = ''
        this.searchObj.endTime = ''
        this.fetchDataById()
      }
    },

    // 每页展示条数的改变，size：回调函数, 表示当前选中的展示条数
    changePageSize(size) {
      this.limit = size
      this.fetchDataById()
    },

    // 翻页，page：回调函数, 表示当前选中的页码
    changeCurrentPage(page) {
      this.page = page
      this.fetchDataById()
    },

    back() {
      this.$router.push({ path: '/crawler/list' })
    },

    // 表头style
    headStyle() {
      return 'color: black; backgroundColor: ' + variables.globalStyle
    },

    // 列style
    cellStyle({ row, column, rowIndex, columnIndex }) {
      return 'height: 50px'
    },

    // 弹窗列style
    cellStyle2({ row, column, rowIndex, columnIndex }) {
      const styleObj = {}
      // 遍历 errTypeList 数组
      for (const item of this.errTypeList) {
        if (item === column.property) {
          // 根据条件设置颜色属性
          if (item !== 'info') {
            styleObj.backgroundColor = this.searchObj.status === 0 ? '#FAE3E3' : '#c1f5c1'
          }
          break // 找到目标列后终止循环
        }
      }
      // 合并样式对象
      return Object.assign({ height: '50px' }, styleObj)
    }
  }
}
</script>

<style lang="scss" scoped>
  @import "@/styles/variables.scss";
  .descriptions-class {
    margin-bottom: 30px;
  }
  ::v-deep .descriptions-class .el-descriptions-item__label.is-bordered-label {
    background: $global-style;
    color: black;
  }

</style>
<style>
  /*.custom-box {*/
  /*  height: 900px;*/
  /*  width: 1000px;*/
  /*  overflow-y: auto;*/
  /*  overflow-x: auto;*/
  /*}*/
  .right-toolbarClass {
    flex: 1;
    text-align: right;
  }

  .dialog {
    width: 3000px;
    position: fixed;
    margin-left: -1450px;
    margin-top: -450px;
    left: 50%;
    top: 50%;
    z-index: 1
  }

  .vm--container {
    z-index: 9999 !important;
  }

  .el-loading-mask {
    z-index: 1;
    /*background-color: rgb(255,255,255,0);*/
  }

  .vm--modal {
    top: 80px !important;
    left: 500px !important;
    height: 800px !important;
    width: 1000px !important;
    z-index: 9999 !important;
  }

  .fixDialog-tag {
    margin-top: 5px;
  }

  .table2 .el-form-item {
    margin-bottom: 0;
  }

  iframe {
    height: 745px;
    width: 1002px;
    margin-left: -2px;
  }

  .separator {
    border-top: 1px solid black;
  }

  .fileTableClass {
    margin: 10px 10px 10px 10px;
    max-height: 300px;
    overflow-y: scroll;
  }
</style>
